package ctn.web.home.controller;

import java.io.File;
import java.io.FileInputStream;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.jmesa.core.filter.DateFilterMatcher;
import org.jmesa.core.filter.MatcherKey;
import org.jmesa.limit.Limit;
import org.jmesa.model.PageItems;
import org.jmesa.model.TableModel;
import org.jmesa.model.TableModelUtils;
import org.jmesa.view.component.Table;
import org.jmesa.view.editor.CellEditor;
import org.jmesa.view.editor.DateCellEditor;
import org.jmesa.view.html.HtmlBuilder;
import org.jmesa.view.html.component.HtmlColumn;
import org.jmesa.view.html.component.HtmlTable;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import ctn.service.dto.SpecDTO;
import ctn.service.inteface.SpecService;
import ctn.util.DownloadHelper;
import ctn.util.MimeContentType;
import ctn.util.StringUtils;
import ctn.util.jmesa.PageFilter;
import ctn.util.jmesa.PageSorter;
import ctn.util.jmesa.PaginationCriteria;
import ctn.util.jmesa.TableFacadeUtils;

@Controller
public class SpecController {
	@Autowired
	private SpecService specServiceImpl;
	@RequestMapping(value="/main/listSpec")
	public ModelAndView listSpec(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		ModelAndView mv=new ModelAndView("spec/specShow");
		TableModel tableModel = new TableModel("listspec", request, response);
		tableModel.setStateAttr("restore");
		final Long funidParm;
		if(!StringUtils.isEmptyString(request.getParameter("funid"))&&!"null".equalsIgnoreCase(request.getParameter("funid"))){
			funidParm=new Long(request.getParameter("funid"));
		}else{
			funidParm=null;
		}
		final Long veridParm;
		if(!StringUtils.isEmptyString(request.getParameter("verid"))&&!"null".equalsIgnoreCase(request.getParameter("verid"))){			
			veridParm=new Long(request.getParameter("verid"));
		}else{
			veridParm=null;
		}
		final PaginationCriteria criteria = new PaginationCriteria();
		tableModel.addFilterMatcher(new MatcherKey(Date.class, "createDate"), new DateFilterMatcher("yyyy-MM-dd"));
		tableModel.setItems(new PageItems() {

			@Override
			public int getTotalRows(Limit limit) {
				PageFilter pageFilter = TableFacadeUtils.getPageFilter(limit,
						SpecDTO.class);
				if(null!=veridParm){
					pageFilter.addFilter("verid", veridParm);
				}
				if(null!=funidParm){
					pageFilter.addFilter("funid", funidParm);
				}
				criteria.setPageFilter(pageFilter);

				return specServiceImpl.getListSpecCount(criteria).intValue();
			}

			@Override
			public List<SpecDTO> getItems(Limit limit) {
				PageSorter pageSorter = TableFacadeUtils.getPageSorter(limit);
				int rowStart = limit.getRowSelect().getRowStart();
				int rowEnd = limit.getRowSelect().getRowEnd();
				criteria.setPageSorter(pageSorter);
				criteria.setRowStart(rowStart);
				criteria.setRowEnd(rowEnd);
				return specServiceImpl.getListSpec(criteria);
			}
		});
	       tableModel.setTable(getHtmlTable());
		   String view = tableModel.render();
	        if (view == null) {
	            return null; // an export
	        } else {
	            // Setting a parameter to signal that this is an Ajax request.
	            String ajax = request.getParameter("ajax");
	            if (ajax != null && ajax.equals("true")) {
	                byte[] contents = view.getBytes();
	                response.getOutputStream().write(contents);
	                return null;
	            } else { // Not using Ajax if invoke the controller for the first time.
	                mv.addObject("wplughtml", view); // Set the Html in the request for the JSP.
	            }
	        }

	        return mv;
	}
	@RequestMapping(value="/main/downspec")
	public void downSpec(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		String id=request.getParameter("id");
		if(StringUtils.isEmptyString(id)){
			return;
		}
		String filePath=specServiceImpl.getFilePath(id);
		File file=new File(filePath);
		FileInputStream inputStream=new FileInputStream(file);
		DownloadHelper.prepareDownload(response, MimeContentType.getContentType(file), file.getName(), inputStream, false);
	}
	@RequestMapping(value="/main/openspec")
	public void openSpec(HttpServletRequest request,
			HttpServletResponse response) throws Exception{
		String id=request.getParameter("id");
		if(StringUtils.isEmptyString(id)){
			return;
		}
		String filePath=specServiceImpl.getFilePath(id);
		File file=new File(filePath);
		FileInputStream inputStream=new FileInputStream(file);
		DownloadHelper.prepareDownload(response, MimeContentType.getContentType(file), file.getName(), inputStream, true);
	}
	private Table getHtmlTable() {
        HtmlTable htmlTable  = TableModelUtils.createHtmlTable("specID","proName","funName","specTyp","specName","createUserName","createDate","action");
        
        htmlTable.setStyle("width:90%;");
        htmlTable.setCaption("查询文档");
        htmlTable.getRow().getColumn("specID").setTitle("编号");
        htmlTable.getRow().getColumn("specID").setWidth("5%");
        htmlTable.getRow().getColumn("proName").setTitle("项目名称");
        htmlTable.getRow().getColumn("proName").setWidth("10%");
        htmlTable.getRow().getColumn("funName").setTitle("模块名称");
        htmlTable.getRow().getColumn("funName").setWidth("10%");
        htmlTable.getRow().getColumn("specTyp").setTitle("文档类型");
        htmlTable.getRow().getColumn("specTyp").setWidth("10%");
        htmlTable.getRow().getColumn("specName").setTitle("文档名称");
        htmlTable.getRow().getColumn("specName").setWidth("20%");
        htmlTable.getRow().getColumn("specName").setTitle("创建者");
        htmlTable.getRow().getColumn("specName").setWidth("10%");
        htmlTable.getRow().getColumn("createDate").setTitle("创建时间");
        htmlTable.getRow().getColumn("createDate").setWidth("15%");
        htmlTable.getRow().getColumn("createDate").setCellEditor(new DateCellEditor("yyyy-MM-dd"));
     
        HtmlColumn action=htmlTable.getRow().getColumn("action");
        action.setTitle("操作");
        action.setWidth("20%");
        action.setFilterable(false);
        action.setCellEditor(new CellEditor() {
			
			@Override
			public Object getValue(Object item, String property, int rowcount) {
				SpecDTO dto=(SpecDTO)item;
				HtmlBuilder html = new HtmlBuilder(); 
				html.ahref("downspec?id="+dto.getSpecID(), "下载").aEnd();
				html.nbsp();
				html.ahref("openspec?id="+dto.getSpecID(), "打开").aEnd();
				return html.toString();
			}
		});
        return htmlTable;
    }
}
